package ESP.Util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Flags.Flag;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mail {
	
	private String host = "smtp.126.com";
	private String name = "esp_gdut";
	private String password = "ESP_gdut2012";
	
	/**
	 *  重置密码
	 * @return 发送的随机密码
	 * @param 用户注册邮箱
	 */
	public String sendPsw2mail(String addressTo){
		String newPassword = null;
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		
		MimeMessage message = new MimeMessage(session);
		//邮件内容
		try {
			newPassword = RandomPassword.getPassword(6);
			message.setContent("init password", "text/plain");
			//邮件主题
			message.setSubject("登录密码重置");
			//过程加密
			message.setContentID("To:"+addressTo);
			message.setContentMD5("To:"+addressTo);
			message.setText("亲：<br/>" +
					"&nbsp;&nbsp;&nbsp;&nbsp;系统已将您的密码重置为<i> "+newPassword+" </i>，登录后请及时修改密码！" +
							"<br/><br/><br/>" +
							"<a href='javascript:void(0)'>此邮件由系统自动发送，无需回复！</a>", "utf-8", "html");
			
			//发件人
			Address fromAddress = new InternetAddress("esp_gdut@126.com", "专业英语学习交流（ESP）系统"); 
			message.setFrom(fromAddress);
			//收件人
			Address toAddress = new InternetAddress(addressTo);
			message.addRecipient(Message.RecipientType.TO, toAddress);
			//设置删除标志
			message.setFlag(Flag.DELETED, true);
			//保存邮件
			message.saveChanges();
			//开启debug模式 
			session.setDebug(true);
			//连接发件箱服务器，并发生邮件
			Transport transport = session.getTransport("smtp"); 
			transport.connect(host, name, password);
			transport.sendMessage(message, message.getAllRecipients()); 
			transport.close();
			return newPassword;
		}catch (SendFailedException e) {
			e.printStackTrace();
			return null;
		} catch (MessagingException e) {
			e.printStackTrace();
			return null;
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}catch (NoClassDefFoundError e) {
			e.printStackTrace();
			return null;
		}
		
	}
}
